﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MusicStore.Silverlight.Helpers;
using MusicStore.Silverlight.MusicStoreService;
using System.Linq;
using MusicStore.Silverlight.Views;
using Castle.Core.Logging;
using MusicStore.Silverlight.Infrastructure;
using Structura.Silverlight.Infrastructure.ViewModel;
using MusicStore.Silverlight.Commands;

namespace MusicStore.Silverlight.ViewModels
{
	/// <summary>
	/// glues the interface with the data model, exposes the data that will be used by the view
	/// </summary>
	public class SearchViewModel :  ViewModel, ISearchViewModel
	{
		public SearchViewModel()
		{
			SearchResults = new PagedCollectionView(_internalSearchResult);
		}

		public new ISearchView View { get { return (this as IViewModel).View as ISearchView; } }

		public ILogger Logger { get; set; }

        public SearchCommand SearchCommand { get; set; }

        public NavigateToAlbumCommand OpenAlbumCommand { get; set; }

		/// <summary>
		/// collection that holds the actual data
		/// </summary>
		private readonly ObservableCollection<AlbumSummary> _internalSearchResult = new ObservableCollection<AlbumSummary>();

		/// <summary>
		/// object that will be used by the binding to expose the collection of data resulting from the search
		/// </summary>
		public PagedCollectionView SearchResults { get; set; }

		/// <summary>
		/// performs an asyncronous search throught the webservice and returns the results filling in the SearchResults collection
		/// </summary>
		/// <param name="query"></param>
		public void PerformSearch(string query)
		{
			IsBusy = true;
			MusicStoreServiceClient service = ServiceHelper.GetServiceClient(); ;
			service.SearchAlbumsCompleted += (sender, e) =>
			                                 	{
																if (e.Error == null)
																{
																	_internalSearchResult.Clear();
																	foreach (var result in e.Result)
																		_internalSearchResult.Add(result);
																	Logger.Info("VM - Search Completed");
																	IsBusy = false;
																}
																else
																{
																	Logger.ErrorFormat(e.Error, "VM - Error performing search with query: {0}", query);
																	IsBusy = false;
																	throw e.Error;
																}
			                                 	};
			Logger.InfoFormat("VM - Performing search with query: {0}", query);
			service.SearchAlbumsAsync(query);
		}

	}
}
